const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID

  try {
    // 获取用户信息
    const userResult = await db.collection('users').where({
      _openid: openid
    }).get()

    if (userResult.data.length === 0) {
      return {
        success: false,
        message: '用户不存在'
      }
    }

    const user = userResult.data[0]
    const currentLevel = user.memberLevel || 1
    const totalConsumption = user.totalConsumption || 0

    // 获取下一个等级信息
    const nextLevelResult = await db.collection('member_levels').where({
      level: currentLevel + 1
    }).get()

    if (nextLevelResult.data.length === 0) {
      return {
        success: false,
        message: '已是最高等级'
      }
    }

    const nextLevel = nextLevelResult.data[0]

    // 检查是否满足升级条件
    if (totalConsumption < nextLevel.upgradeCondition.value) {
      return {
        success: false,
        message: `消费金额不足，还需消费${nextLevel.upgradeCondition.value - totalConsumption}元`
      }
    }

    // 更新用户会员等级
    await db.collection('users').doc(user._id).update({
      data: {
        memberLevel: nextLevel.level,
        updatedAt: new Date()
      }
    })

    return {
      success: true,
      message: `恭喜升级为${nextLevel.name}！`,
      data: {
        newLevel: nextLevel.level,
        levelName: nextLevel.name
      }
    }
  } catch (error) {
    console.error('会员升级失败:', error)
    return {
      success: false,
      message: '升级失败，请稍后重试'
    }
  }
}